#include "mainwindow.h"
#include <QPushButton>
#include "ui_MainWindow.h"
#include <QVBoxLayout>
#include <QSplitter>
#include <QDebug>
#include <QLineEdit>
#include <QTableView>
#include <QHeaderView>
#include <QTimer>
#include <QMessageBox>
#include <QStack>
#include <QQueue>
#include <QThreadPool>
#include <QKeyEvent>

#include "ConstValue.h"
#include "SearchTask.h"



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    fileSystemModel(new QFileSystemModel(this)){
    ui->setupUi(this);
    _init();
    this->showMaximized();
}

MainWindow::~MainWindow() {
    delete ui;
}


void MainWindow::on_actionSmall_triggered() {
    modifyIconSize(16,100,50);
    ui->actionSmall->setChecked(true);
}

void MainWindow::on_actionBig_triggered() {
    modifyIconSize(64,200,128);
    ui->actionBig->setChecked(true);
}

void MainWindow::on_actionMiddle_triggered() {
    modifyIconSize(32,150,80);
    ui->actionMiddle->setChecked(true);
}

void MainWindow::on_actionDetail_triggered() {
    resetCheckStatus();
    ui->actionDetail->setChecked(true);
    stackWidget->setCurrentIndex(0);
}

void MainWindow::on_actionList_triggered() {
    resetCheckStatus();
    ui->actionList->setChecked(true);
    listView->setViewMode(QListView::ListMode);
    listView->setIconSize(QSize(16, 16));
    stackWidget->setCurrentIndex(1);
}

void MainWindow::on_actionNew_triggered() {
    MainWindow *newWindow = new MainWindow(this);
    newWindow->show();
    newWindow->setWindowTitle("资源管理系统");
}

void MainWindow::returnToNormalView() {
    tableView->setModel(fileSystemModel);
    listView->setModel(fileSystemModel);
    M_Thread::isStop= true;
    searchResultsModel->removeRows(0, searchResultsModel->rowCount());
}

bool MainWindow::isProxyModelIndex(const QModelIndex &index) const {
    return index.isValid() && index.model() == folderOnlyProxyModel;
}


void MainWindow::modifyIconSize(int iconSize,int x,int y) {
    resetCheckStatus();
    stackWidget->setCurrentIndex(1);
    listView->setViewMode(QListView::IconMode);
    listView->setIconSize(QSize(iconSize,iconSize));
    listView->setGridSize(QSize(x,y));
    listView->setResizeMode(QListView::Adjust);
}

void MainWindow::resetCheckStatus(bool checked) {
    ui->actionBig->setChecked(checked);
    ui->actionMiddle->setChecked(checked);
    ui->actionSmall->setChecked(checked);
    ui->actionDetail->setChecked(checked);
    ui->actionList->setChecked(checked);
    stackWidget->setCurrentIndex(1);
}

void MainWindow::checkStackQueueEnable() {
    back_btn->setEnabled(true);
    next_btn->setEnabled(true);
    if (indexBack->isEmpty()) {
        back_btn->setEnabled(false);
    }
    if (indexNext->isEmpty()) {
        next_btn->setEnabled(false);
    }
    if (indexBack->size()>= M_Stack::maxStack) {
        indexBack->removeFirst();
    }
    if (indexNext->size()>= M_Stack::maxStack) {
        indexNext->removeFirst();
    }
}

/**
 * 根据模型来更新索引
 * @param index,普通索引
 */
void MainWindow::viewUpdated(QModelIndex index) {
    QModelIndex treeIndex;
    if (!isProxyModelIndex(index)) {
        treeIndex = folderOnlyProxyModel->mapFromSource(index);
    }else {
        treeIndex=index;
        index=folderOnlyProxyModel->mapToSource(index);
    }

    up_btn->setEnabled(true);
    if (fileSystemModel->filePath(index)==fileSystemModel->rootPath()) {
        up_btn->setEnabled(false);
    }
    treeView->setCurrentIndex(treeIndex);
    listView->setRootIndex(index);
    tableView->setRootIndex(index);
    handleTextDisplay(index);
    checkStackQueueEnable();
}

/**
 * 显示当前路径
 * @param index
 */
void MainWindow::showStatusMessage(const QString &message) {
    ui->statusbar->showMessage(message);
}


void MainWindow::handleRunnableResult(QList<QModelIndex> results) {
    std::lock_guard lock(result_mutex);
    M_Thread::taskFinsh++;
    qDebug()<<"autuclTread"<<M_Thread::autuclTread;
    qDebug() << "taskFinsh:" << M_Thread::taskFinsh;
    if (results.isEmpty()) {
        return;
    }
    for (const QModelIndex &index : results) {
        if (index.isValid()) {
            QFileInfo fileInfo = fileSystemModel->fileInfo(index);
            QList<QStandardItem*> rowItems;
            QStandardItem *nameItem = new QStandardItem(fileInfo.fileName());
            nameItem->setIcon(fileSystemModel->fileIcon(index));
            nameItem->setData(index, Qt::UserRole);
            QStandardItem *typeItem = new QStandardItem(fileInfo.isDir() ? "文件夹" : "文件");
            QStandardItem *sizeItem = new QStandardItem(fileInfo.size() > 1024 ? QString::number(fileInfo.size() / 1024) + "KB" : QString::number(fileInfo.size()) + "B");
            QStandardItem *timeItem = new QStandardItem(fileInfo.lastModified().toString("yyyy-MM-dd hh:mm:ss"));
            rowItems.append(nameItem);
            rowItems.append(sizeItem);
            rowItems.append(typeItem);
            rowItems.append(timeItem);
            searchResultsModel->appendRow(rowItems);
        }
    }
    tableView->setModel(searchResultsModel);
    listView->setModel(searchResultsModel);
    tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    tableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    tableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
    tableView->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);
    tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    if (M_Thread::taskFinsh==M_Thread::autuclTread) {
        M_Thread::taskFinsh=0;
        M_Thread::autuclTread = 0;
        showStatusMessage(QString("搜索完成，找到 %1 个匹配项").arg(searchResultsModel->rowCount()));
    }
}

/**
 * back按钮处理槽
 */
void MainWindow::backBtnClicked() {
    QModelIndex index = indexBack->pop();
    QModelIndex sourceIndex = folderOnlyProxyModel->mapToSource(treeView->currentIndex());
    indexNext->push(sourceIndex);
    QModelIndex treeIndex = folderOnlyProxyModel->mapFromSource(index);
    viewUpdated(treeIndex);
}

/**
 * next按钮处理槽
 */
void MainWindow::nextBtnClicked() {
    auto index = indexNext->pop();
    QModelIndex sourceIndex = folderOnlyProxyModel->mapToSource(treeView->currentIndex());
    indexBack->push(sourceIndex);
    QModelIndex treeIndex = folderOnlyProxyModel->mapFromSource(index);
    viewUpdated(treeIndex);
}

/**
 * up按钮点击处理槽
 */
void MainWindow::upBtnClicked() {
    // treeView->currentIndex() 返回的是代理模型索引
    QModelIndex currentProxyIndex = treeView->currentIndex();
    // qDebug() << "currentProxyIndex:" << currentProxyIndex;
    // qDebug()<<fileSystemModel->filePath(folderOnlyProxyModel->mapToSource(currentProxyIndex));
    qDebug()<<fileSystemModel->rootPath();
    if (!currentProxyIndex.isValid()) {
        return;
    }
    // 使用代理模型获取父级索引
    QModelIndex parentProxyIndex = folderOnlyProxyModel->parent(currentProxyIndex);

    // 如果没有父级（根目录），则使用根路径索引
    if (!parentProxyIndex.isValid()) {
        QString rootPath = fileSystemModel->rootPath();
        QModelIndex rootSourceIndex = fileSystemModel->index(rootPath);
        parentProxyIndex = folderOnlyProxyModel->mapFromSource(rootSourceIndex);
        if (!parentProxyIndex.isValid()) {
            return;
        }
    }
    if (indexBack->count(lastModelIndex) == 0)
        indexBack->push(lastModelIndex);

    QModelIndex sourceIndex = folderOnlyProxyModel->mapToSource(parentProxyIndex);
    indexBack->push(lastModelIndex);
    viewUpdated(parentProxyIndex);
    lastModelIndex = sourceIndex;
    checkStackQueueEnable();
}


/**
 * 树view点击处理槽
 * @param index
 */
void MainWindow::treeViewClicked(const QModelIndex &index) {
    returnToNormalView();
    if (indexBack->count(lastModelIndex)==0)
        indexBack->push(lastModelIndex);
    // 将代理模型的索引转换为源模型索引
    QModelIndex sourceIndex = folderOnlyProxyModel->mapToSource(index);
    lastModelIndex = sourceIndex;
    indexNext->clear();
    viewUpdated(sourceIndex);
}

/**
 * 处理文件或者文件夹对应的点击
 * @param index
 * @return
 */
bool MainWindow::handleFileOrDirectory(const QModelIndex &index) {
    if (indexBack->count(lastModelIndex)==0)
        indexBack->push(lastModelIndex);
    QString filePath = fileSystemModel->filePath(index);
    QFileInfo fileInfo(filePath);
    if (fileInfo.isDir()) {
        viewUpdated(index);
    } else {
        QDialog dialog;
        dialog.setWindowTitle("打开文件");
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QMessageBox::warning(&dialog, "错误", "无法打开文件");
            return true;
        }
        dialog.exec();
        showStatusMessage("已打开文件: " + fileInfo.fileName());
    }
    lastModelIndex = index;
    checkStackQueueEnable();
    return false;
}

/**
 * 数据双击处理槽
 * @param index
 */
void MainWindow::DataDoubleClicked(const QModelIndex &index) {
    if (!index.isValid()) {
        return;
    }
    if (tableView->model() == searchResultsModel) {
        // 从搜索结果中获取原始索引
        QStandardItem *item = searchResultsModel->item(index.row(), 0); // 第一列是文件名
        if (item) {
            QVariant data = item->data(Qt::UserRole);
            if (data.isValid()) {
                // 获取原始文件系统索引
                QModelIndex originalIndex = data.toModelIndex();
                if (originalIndex.isValid()) {
                    // 使用原始索引处理文件/目录
                    handleFileOrDirectory(originalIndex);
                }
            }
        }
    }else
        handleFileOrDirectory(index);
}


/**
 * 处理combox框选中变化信号
 * @param text
 */
void MainWindow::handleBtnPathEnter(const QString &text) {
    showStatusMessage("正在搜索路径：" + text);
    //清空上次的搜索结果
    if (text.isEmpty()) {
        return;
    }

    QString normalizedPath = QDir::fromNativeSeparators(text);

    int existingIndex = -1;
    for (int i = 0; i < historySearchComBox->count(); ++i) {
        if (QDir::fromNativeSeparators(historySearchComBox->itemText(i)) == normalizedPath) {
            existingIndex = i;
            break;
        }
    }

    QFileInfo fileInfo(normalizedPath);
    if (fileInfo.isAbsolute() && fileInfo.exists()) {
        QModelIndex index = fileSystemModel->index(normalizedPath);

        if (index.isValid()) {
            if (fileInfo.isDir()) {
                viewUpdated(index);
            } else {
                QModelIndex parentIndex = index.parent();
                QModelIndex fileIndex = index;
                tableView->setRootIndex(parentIndex);
                treeView->setCurrentIndex(fileIndex);
                listView->setRootIndex(parentIndex);
                handleTextDisplay(parentIndex);
            }
            if (existingIndex == -1) {
                historySearchComBox->insertItem(0, normalizedPath);
                if (historySearchComBox->count() > 20) {
                    historySearchComBox->removeItem(historySearchComBox->count() - 1);
                }
            } else {
                // 如果路径已存在，只需将其移到最前面
                QString existingText = historySearchComBox->itemText(existingIndex);
                historySearchComBox->removeItem(existingIndex);
                historySearchComBox->insertItem(0, existingText);
                historySearchComBox->setCurrentIndex(0);
            }
        } else {
            showStatusMessage("路径无效或不存在：" + normalizedPath);
        }
    }
}

/**
 * 处理回车键信号
 */
void MainWindow::handleBtnPathEnter() {
    QString text = historySearchComBox->currentText().trimmed();
    if (!text.isEmpty()) {
        handleBtnPathEnter(text);
    }
}

/**
 * 处理当前目录下的文件搜索
 * @param text
 */
/**
 * 处理当前目录下的文件搜索
 * @param text
 */
void MainWindow::handleFileSearch(bool isAll) {

    qDebug()<<"这是一个文件搜索方法";
    M_Thread::isStop=false;
    // todo 终止并不及时，会导致删除数据后，又新加上数据
    searchResultsModel->removeRows(0, searchResultsModel->rowCount());
    M_Thread::taskFinsh=0;
    M_Thread::autuclTread=0;
    // 判断搜索框是否为空
    QString text = searchFileLineEdit->text().trimmed();
    if (text.isEmpty()) {
        returnToNormalView();
        viewUpdated(treeView->currentIndex());
        return;
    }
    QString currentPath = fileSystemModel->rootPath();
    qDebug()<<"=============================";
    qDebug()<<currentPath;
    qDebug()<<"=============================";

    if (tableView->rootIndex().isValid()) {
        currentPath = fileSystemModel->filePath(tableView->rootIndex());
    }

    QDir currentDir(currentPath);
    QFileInfoList fileList = currentDir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);

    QStringList folderPaths;
    QStringList filePaths;
    // 是否搜索所有盘符
    if (isAll) {
        folderPaths.append("C:/");
        folderPaths.append("D:/");
        folderPaths.append("E:/");
    }else {
        //分离文件夹和文件
        for (const QFileInfo &info : fileList) {
            if (info.isDir()) {
                folderPaths.append(info.absoluteFilePath());
            } else {
                filePaths.append(info.absoluteFilePath());
            }
        }
    }

    for (auto &path : folderPaths) {
        qDebug() << "文件夹：" << path;
    }
    for (auto &path : filePaths) {
        qDebug() << "文件：" << path;
    }
    qDebug() << "找到" << folderPaths.size() << "个文件夹，" << filePaths.size() << "个文件";

    int folderThreadCount=M_Thread::threadCount-1;
    int perThreadNum=1;    //每个线程处理的文件夹数
    if (folderPaths.size()>folderThreadCount) {
        perThreadNum=folderPaths.size()/folderThreadCount;
    }else
        folderThreadCount=folderPaths.size();

    for (int i=0;i<folderThreadCount;i++) {
        QList<QString> folderPath;
        if (i==folderThreadCount-1) {
            folderPath=folderPaths.mid(i*perThreadNum,folderPaths.size()-i*perThreadNum);
        }
        folderPath=folderPaths.mid(i*perThreadNum,perThreadNum);
        QThreadPool::globalInstance()->start(new SearchTask(this,folderPath,text));
        qDebug()<<"线程"<<i<<"启动"<<"处理"<<folderPath;
    }

    M_Thread::autuclTread=folderThreadCount;
    if (filePaths.size()!=0) {
        // 使用一个线程处理所有文件
        qDebug() << "使用1个线程处理" << filePaths.size() << "个文件";
        QThreadPool::globalInstance()->start(new SearchTask(this, filePaths, text,false));
        M_Thread::autuclTread+=1;
    }
    qDebug() << "总共启动" << M_Thread::autuclTread << "个线程";
}

/**
 * 处理数据展示
 * @param index
 */
void MainWindow::handleTextDisplay(const QModelIndex &index) {
    QString filePath = fileSystemModel->filePath(index);
    QString dirName = filePath.isEmpty() ? "根目录" : QFileInfo(filePath).fileName();
    if (dirName.isEmpty()) {
        dirName=filePath;
    }

    historySearchComBox->lineEdit()->setText(filePath);
    searchFileLineEdit->clear();
    searchFileLineEdit->setPlaceholderText("在" + dirName + "下进行搜索");
    handleStatusBarDisplay(filePath);
}


/**
 * 状态栏显示
 * @param filePath
 */
void MainWindow::handleStatusBarDisplay(const QString &filePath) {
    QString dirName = filePath.isEmpty() ? "根目录" : QFileInfo(filePath).fileName();
    // 使用 QDir 计算项目数量
    QDir dir(filePath);
    if (filePath.isEmpty()) {
        dir = QDir::root(); // 如果是空路径，使用根目录
    }

    // 获取所有文件和文件夹
    QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);

    int fileCount = 0;
    int folderCount = 0;

    for (const QFileInfo &info : entries) {
        if (info.isDir()) {
            folderCount++;
        } else {
            fileCount++;
        }
    }
    // 更新状态栏
    showStatusMessage(QString("当前目录: %1 | 文件夹: %2 | 文件: %3 | 总计: %4")
                              .arg(dirName)
                              .arg(folderCount)
                              .arg(fileCount)
                              .arg(folderCount + fileCount));
}

/**
 * 事件过滤
 * @param obj
 * @param event
 * @return
 */
bool MainWindow::eventFilter(QObject *obj, QEvent *event) {
    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);

        if (obj == tableView || obj == listView || obj == treeView) {
            if (keyEvent->key() == Qt::Key_F2) {
                // F2 重命名
                QModelIndex currentIndex = qobject_cast<QAbstractItemView*>(obj)->currentIndex();
                if (currentIndex.isValid()) {
                    m_contextMenu->setCurrentIndex(currentIndex);
                    m_contextMenu->onRenameTriggered();
                    return true;
                }
            } else if (keyEvent->key() == Qt::Key_Delete) {
                QModelIndex currentIndex = qobject_cast<QAbstractItemView*>(obj)->currentIndex();
                if (currentIndex.isValid()) {
                    m_contextMenu->setCurrentIndex(currentIndex);
                    m_contextMenu->onDeleteTriggered();
                    return true;
                }
            }
            // Ctrl + V 粘贴
            else if (keyEvent->key() == Qt::Key_V && keyEvent->modifiers() & Qt::ControlModifier) {
                // 粘贴操作需要当前视图
                m_contextMenu->setCurrentView(qobject_cast<QWidget*>(obj));
                m_contextMenu->onPasteTriggered();
                return true;
            }
            // Ctrl + C 复制
            else if (keyEvent->key() == Qt::Key_C && keyEvent->modifiers() & Qt::ControlModifier) {
                QModelIndex currentIndex = qobject_cast<QAbstractItemView*>(obj)->currentIndex();
                if (currentIndex.isValid()) {
                    m_contextMenu->setCurrentIndex(currentIndex);
                    m_contextMenu->onCopyTriggered();
                    return true;
                }
            }
            // Ctrl + X 剪切
            else if (keyEvent->key() == Qt::Key_X && keyEvent->modifiers() & Qt::ControlModifier) {
                QModelIndex currentIndex = qobject_cast<QAbstractItemView*>(obj)->currentIndex();
                if (currentIndex.isValid()) {
                    m_contextMenu->setCurrentIndex(currentIndex);
                    m_contextMenu->onCutTriggered();
                    return true;
                }
            }
            // Ctrl + A 全选
            else if (keyEvent->key() == Qt::Key_A && keyEvent->modifiers() & Qt::ControlModifier) {
                QAbstractItemView* view = qobject_cast<QAbstractItemView*>(obj);
                view->selectAll();
                return true;
            }
            // Enter/Return 打开
            else if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) {
                QModelIndex currentIndex = qobject_cast<QAbstractItemView*>(obj)->currentIndex();
                if (currentIndex.isValid()) {
                    m_contextMenu->setCurrentIndex(currentIndex);
                    m_contextMenu->onOpenTriggered();
                    return true;
                }
            }
        }
    }
    return QMainWindow::eventFilter(obj, event);
}


void MainWindow::onTableHeaderClicked(int logicalIndex)
{
    QString currentPath = fileSystemModel->filePath(tableView->rootIndex());
    if (currentPath.isEmpty()) {
        currentPath = fileSystemModel->rootPath();
    }
    //暂存根路径
    QString rootPath = fileSystemModel->rootPath();
    fileSystemModel->setRootPath(currentPath);

    if(logicalIndex == m_sortColumn)
    {
        m_sortOrder = (m_sortOrder == Qt::AscendingOrder)
                ? Qt::DescendingOrder
                : Qt::AscendingOrder;
    }
    else
    {
        m_sortColumn = logicalIndex;
        m_sortOrder = Qt::AscendingOrder;
    }
    fileSystemModel->sort(m_sortColumn,m_sortOrder);
    fileSystemModel->setRootPath(rootPath);
}

/**
 * 实现上下文菜单的槽函数
 * @param pos
 */
void MainWindow::showContextMenu(const QPoint &pos) {
    // 它返回发送信号的对象指针
    // 获取发送信号的视图
    QWidget *senderView = qobject_cast<QWidget*>(sender());
    if (senderView) {
        // 显示菜单
        m_contextMenu->showMenu(senderView, pos);
    }
}

void MainWindow::initModelView() {
    cenWidget = this->centralWidget();
    if (cenWidget->layout()) {
        delete cenWidget->layout();
    }
    stackWidget = new QStackedWidget(this);

    //模型视图初始化设置
    fileSystemModel->setRootPath(QDir::rootPath());
    fileSystemModel->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
    folderOnlyProxyModel = new FolderOnlyProxyModel(this);
    folderOnlyProxyModel->setSourceModel(fileSystemModel);

    tableView = new QTableView(this);
    treeView = new QTreeView(this);
    listView = new QListView(this);
    treeView->setModel(folderOnlyProxyModel);
    tableView->setModel(fileSystemModel);
    listView->setModel(fileSystemModel);
    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    treeView->hideColumn(1);
    treeView->hideColumn(2);
    treeView->hideColumn(3);
    treeView->setHeaderHidden(true);

    tableView->setFrameStyle(QFrame::NoFrame);
    tableView->setSortingEnabled(true);
    tableView->verticalHeader()->hide();
    tableView->horizontalHeader()->setSectionsClickable(true);
    tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableView->setShowGrid(false);
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    tableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);

    m_sortColumn = 0;
    m_sortOrder = Qt::AscendingOrder;
    connect(tableView->horizontalHeader(),&QHeaderView::sectionClicked,
            this,&MainWindow::onTableHeaderClicked);
    connect(treeView, &QTreeView::clicked, this, &MainWindow::treeViewClicked);
    connect(tableView,&QTreeView::doubleClicked, this, &MainWindow::DataDoubleClicked);
    connect(listView,&QTreeView::doubleClicked, this, &MainWindow::DataDoubleClicked);
    stackWidget->addWidget(tableView);
    stackWidget->addWidget(listView);
    stackWidget->setCurrentIndex(0);

    // 创建 splitter 并添加到布局中
    splitter = new QSplitter(Qt::Horizontal,this);
    splitter->addWidget(treeView);
    splitter->addWidget(stackWidget);
    splitter->setStretchFactor(1,3);
}

void MainWindow::initMenu() {
    // 初始化右键菜单
    m_contextMenu = new FileContextMenu(this, fileSystemModel, this);
    // 为所有视图设置上下文菜单策略并连接信号
    treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(treeView, &QTreeView::customContextMenuRequested,
            this, &MainWindow::showContextMenu);
    listView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(listView, &QListView::customContextMenuRequested,
            this, &MainWindow::showContextMenu);
    tableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(tableView, &QTableView::customContextMenuRequested,
            this, &MainWindow::showContextMenu);
    tableView->installEventFilter(this);
    listView->installEventFilter(this);
    treeView->installEventFilter(this);
}

void MainWindow::initOperationBtn() {
    //创建前进回退按钮
    indexBack=new QStack<QModelIndex>();
    indexNext=new QStack<QModelIndex>();
    back_btn = new QPushButton(this);
    QIcon backIcon = style()->standardIcon(QStyle::SP_ArrowBack);
    back_btn->setIcon(backIcon);
    back_btn->setIconSize(QSize(24, 24));
    back_btn->setFixedSize(32, 32);
    back_btn->setToolTip("返回上一层");
    next_btn = new QPushButton(this);
    QIcon nextIcon = style()->standardIcon(QStyle::SP_ArrowForward);
    next_btn->setIcon(nextIcon);
    next_btn->setIconSize(QSize(24, 24));
    next_btn->setFixedSize(32, 32);
    next_btn->setToolTip("进入下一层");
    up_btn = new QPushButton(this);
    QIcon returnIcon = style()->standardIcon(QStyle::SP_ArrowUp);
    up_btn->setIcon(returnIcon);
    up_btn->setIconSize(QSize(24, 24));
    up_btn->setFixedSize(32, 32);
    up_btn->setToolTip("返回上一级目录");
    up_btn->setEnabled(false);
    connect(back_btn, &QPushButton::clicked, this, &MainWindow::backBtnClicked);
    connect(next_btn, &QPushButton::clicked, this, &MainWindow::nextBtnClicked);
    connect(up_btn, &QPushButton::clicked, this, &MainWindow::upBtnClicked);
    lastModelIndex=treeView->currentIndex();
    checkStackQueueEnable();
}

void MainWindow::initSearchEdit() {
    //创建文件路径搜索框
    historySearchComBox = new QComboBox(this);
    historySearchComBox->setEditable(true);
    connect(historySearchComBox, &QComboBox::textActivated,
            this, static_cast<void(MainWindow::*)(const QString&)>(&MainWindow::handleBtnPathEnter));
    // 连接无参数的槽函数
    connect(historySearchComBox->lineEdit(), &QLineEdit::returnPressed,
            this, static_cast<void(MainWindow::*)()>(&MainWindow::handleBtnPathEnter));

    //创建文件搜索框
    searchFileLineEdit = new QLineEdit(this);
    // 初始化搜索结果模型
    searchResultsModel = new QStandardItemModel(this);
    searchResultsModel->setColumnCount(4);
    searchResultsModel->setHorizontalHeaderLabels(QStringList() << "文件名" << "大小" << "类型" << "修改时间");
    connect(searchFileLineEdit, &QLineEdit::returnPressed, this,&MainWindow::handleFileSearch);
}

void MainWindow::initLayOut() {
    // 创建顶部布局并添加按钮和搜索框
    topLayout = new QHBoxLayout(this);
    topLayout->addWidget(back_btn,1);
    topLayout->addWidget(next_btn,1);
    topLayout->addWidget(up_btn,1);
    topLayout->addWidget(historySearchComBox,4);
    topLayout->addWidget(searchFileLineEdit,4);

    // 创建布局并添加 splitter
    layout = new QVBoxLayout(this);
    layout->addLayout(topLayout);
    layout->addWidget(splitter);
    cenWidget->setLayout(layout);

    this->setWindowTitle("资源管理系统");
    this->setWindowIcon(style()->standardIcon(QStyle::SP_DesktopIcon));
}

/**
 * 初始化方法
 */
void MainWindow::_init() {
    //初始化模型和视图
    initModelView();
    //初始化右键菜单
    initMenu();
    //初始化操作按钮
    initOperationBtn();
    // 初始化文件搜索框
    initSearchEdit();
    // 初始化布局
    initLayOut();
}
